package com.ldg.user.controller;

import cn.hutool.crypto.SecureUtil;

import com.ld.utils.PhoneFormatCheckUtils;
import com.ld.pojo.R;
import com.ldg.user.entity.TbUser;
import com.ldg.user.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("user")
public class UserController {
	@Autowired
	private TbUserService userService;

	//1. 发送手机验证码
	@GetMapping("getCode/{phone}")
	public R getCode(@PathVariable String phone){
		//1. 验证手机号是否合法
		if(PhoneFormatCheckUtils.isPhoneLegal(phone)){
			userService.sendCode(phone);
		}
		//2. 返回
		return R.ok();
	}

	//2. 保存用户
	@PostMapping("save")
	public R save(TbUser user, String validCode){
		if(userService.isExistCode(user.getPhone(),validCode)){
			user.setPassword(SecureUtil.md5(user.getPassword()));
			user.setCreated(new Date());
			user.setUpdated(new Date());
			userService.save(user);
		}

		return R.ok();
	}

	//3. 查看所有用户
	@GetMapping("findAll")
	public R findAll(){
		return R.ok().put("list",userService.list());
	}
}
